package com.cheyun.netsalev3.viewmodel

import android.content.Intent
import android.view.View
import android.widget.DatePicker
import android.widget.TimePicker
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import com.cheyun.netsalev3.bean.CarBrandParam
import com.cheyun.netsalev3.bean.ClueDetails
import com.cheyun.netsalev3.bean.DialogParam
import com.cheyun.netsalev3.bean.KeyValueParam
import com.cheyun.netsalev3.repository.ClueFollowUpRepository
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.view.choosecar.ChooseCarActivity
import com.cheyun.netsalev3.widget.DatePickerFragment
import com.cheyun.netsalev3.widget.MyDialog
import com.cheyun.netsalev3.widget.TimePickerFragment
import com.jeremyliao.liveeventbus.LiveEventBus
import java.io.Serializable
import java.util.*

/**
 * @author Michael
 * @date  2018/12/18 - 14:45.
 */
class EditCarBuyingRecordActivityViewModel(var clueDetails: ClueDetails, var clueFollowUpRepository: ClueFollowUpRepository, var tiCar: Boolean) : BaseViewModel() {
    var listdata = MutableLiveData<List<KeyValueParam>>()
    var temlist = ArrayList<KeyValueParam>()
    var cert_images:ArrayList<String> = arrayListOf()

    var editBtnEnable = MutableLiveData<Boolean>()
    //购车记录
//    var goucarDatakey = arrayOf(
//            "订车品牌:",
//            "订车车系:",
//            "订车车型:",
//            "预定成交时间:",
//            "订单号:",
//            "预订价格:",
//            "订车车辆颜色 ",
//            "订车内饰颜色:",
//            "提车时间:",
//            "车牌号:",
//            "车架号:",
//            "保险公司:",
//            "保单号:",
//            "保险到期日:",
//            "付款方式:",
//            "按揭银行:",
//            "按揭服务费:",
//            "用品销售额:",
//            "会员:",
//            "其他费用:",
//            "提车品牌:",
//            "提车车系:",
//            "提车车型:",
//            "提车车辆颜色:",
//            "提车内饰颜色:"
//    )

    init {
        if (tiCar) {
            temlist.addAll(clueDetails.liftCarlist)
            initTiCar()

        } else {
            //不可编辑
            //配车后
            // 1,开起库存()
            var loginData = MySharedPreferences.getLoginData()
            if(loginData?.channel?.settings?.storage?.state == 1 && !clueDetails.Level.equals("D") && !clueDetails.vin.equals("")){
                clueDetails.buyCarlist[0].isEdit = false
                clueDetails.buyCarlist[1].isEdit = false
                clueDetails.buyCarlist[2].isEdit = false
                clueDetails.buyCarlist[6].isEdit = false
                clueDetails.buyCarlist[7].isEdit = false
            }
            temlist.addAll(clueDetails.buyCarlist)
            initData()
        }
    }
    /**
     * 初始化提车数据
     */
    private fun initTiCar() {
        var baseData = MySharedPreferences.getBaseData()
        //拟购车辆颜色
        var exteriorlist = ArrayList<DialogParam>()
        baseData?.exterior?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                exteriorlist.add(item)
            }
        }
        //拟购内饰颜色
        var interiorlist = ArrayList<DialogParam>()
        baseData?.interior?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                interiorlist.add(item)
            }
        }

//        //保险公司
//        var insurerlist = ArrayList<DialogParam>()
//        MySharedPreferences.getBaseData()?.insurer?.apply {
//            for (i in this) {
//                var item = DialogParam(i.title, i.id.toString())
//                item.ikey = i.ikey
//                insurerlist.add(item)
//            }
//
//        }
        //购买类型
        var purchasetypelist = arrayListOf(
                DialogParam("首购", "1"),
                DialogParam("增购", "2"),
                DialogParam("置换", "3")
        )


        for (item in temlist) {
            item.poplistdata = when (item.key) {
                "提车车辆颜色:" -> exteriorlist
                "提车内饰颜色:" -> interiorlist
                "购买类型:" -> purchasetypelist
//                "保险公司:" -> insurerlist
                else -> ArrayList()
            }
        }
        listdata.postValue(temlist)

    }

    fun initData() {
        var baseData = MySharedPreferences.getBaseData()
        //拟购车辆颜色
        var exteriorlist = ArrayList<DialogParam>()
        baseData?.exterior?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                exteriorlist.add(item)
            }
        }
        //拟购内饰颜色
        var interiorlist = ArrayList<DialogParam>()
        baseData?.interior?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                interiorlist.add(item)
            }
        }
        //支付方式
        var paymentwaylist = ArrayList<DialogParam>()
        baseData?.paymentway?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                paymentwaylist.add(item)
            }
        }
        //按揭银行
        var banklist = ArrayList<DialogParam>()
        baseData?.bank?.apply {
            for (i in this) {
                var item = DialogParam(i.title, i.id.toString())
                banklist.add(item)
            }
        }
        //保险公司
        var insurerlist = java.util.ArrayList<DialogParam>()
//        MySharedPreferences.getBaseData()?.insurer?.apply {
//            for (i in this) {
//                var item = DialogParam(i.title, i.id.toString())
//                item.ikey = i.ikey
//                insurerlist.add(item)
//            }
//
//        }
        //会员
        var mlevellist = ArrayList<DialogParam>()
//        baseData?.mlevel?.apply {
//            for (i in this) {
//                var item = DialogParam(i.title, i.id.toString())
//                mlevellist.add(item)
//            }
//        }
        for (item in temlist) {
            item.poplistdata = when (item.key) {
                "订车车辆颜色:" -> exteriorlist
                "订车内饰颜色:" -> interiorlist
                "保险公司:" -> insurerlist
                "付款方式:" -> paymentwaylist
                "按揭银行:" -> banklist
                "会员:" -> mlevellist
                else -> ArrayList()
            }
        }
        listdata.postValue(temlist)

    }

    //是否开启库存
    var state = MySharedPreferences.getLoginData()?.channel?.settings?.storage?.state ?: 0



    /**
     * 点击item
     */
    fun onClickItem(view: View, item: KeyValueParam, pos: Int) {

        this.pos = pos
        //时间选择
        if (item.type == 1 && item.sontype == 2) {
            showDateTime(view)
        } else {

            if (!item.isEdit){
                MyToast("不能修改")
                return
            }

            when (item.key) {
                "订车品牌:" -> onClicCar(view, 0)
                "订车车系:" -> onClicCar(view, 1)
                "订车车型:" -> onClicCar(view, 2)

                "提车品牌:" -> onClicCar(view, 0)
                "提车车系:" -> onClicCar(view, 1)
                "提车车型:" -> onClicCar(view, 2)
                else -> {
                    if (item.type == 1 && item.sontype == 1)
                        onClickPop(view, item)
                }
            }
        }

    }


    /**
     * 普通选择弹窗
     */
    private fun onClickPop(view: View, item: KeyValueParam) {

        var content = view.context
        if (content is AppCompatActivity) {
            var list = ArrayList<DialogParam>()
            for (it in item.poplistdata) {
                var item = DialogParam(it.name, it.id)
                item.IsSelect = it.IsSelect
                item.ikey = it.ikey
                list.add(item)
            }
            var dialog = MyDialog.newInstance(item.poptitle, list)
            dialog.huidia = this::popHuiDiao
            dialog.show(content.supportFragmentManager, "")
        }


    }

    /**
     * 弹窗确定回调
     */
    fun popHuiDiao(item: DialogParam?) {
        item?.apply {
            temlist[pos].value = this.name
            temlist[pos].id = this.id
        }
    }

    var context: AppCompatActivity? = null
    var timeDate = ""
    var pos = 0
    /**
     * 选择时间
     */
    private fun showDateTime(view: View) {

        var content = view.context
        if (content is AppCompatActivity) {
            this.context = content
            var datePop = DatePickerFragment()
            val c = Calendar.getInstance()
            datePop.maxDate = c.timeInMillis
            datePop.clickOk = this::onDateSet
            datePop.show(content.supportFragmentManager, "")
        }

    }

    var year = 0
    var month = 0
    var day = 0
    /**
     * 日期回调
     */
    fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
        this.year = year
        this.month = month
        this.day = day
        context?.apply {
            var timepop = TimePickerFragment()
            timepop.clickOk = this@EditCarBuyingRecordActivityViewModel::onTimeSet
            timepop.show(this.supportFragmentManager, "")
        }
    }

    fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
        timeDate = FunctionUtils.formatTime(year.toString(), month.toString(), day.toString(), hourOfDay, minute)
        temlist[pos].value = timeDate
        temlist[pos].id = timeDate
    }


    /**
     * 点击 品牌=0 车系=1车型=2
     */
    fun onClicCar(view: View, p: Int) {
        var content = view.context
        if (content is AppCompatActivity) {
            var intent = Intent(view.context, ChooseCarActivity::class.java)
            intent.putExtra("pos", p)
            var car = CarBrandParam(temlist[0].id, temlist[1].id, temlist[2].id,"")
            car.brandname = temlist[0].value
            car.seriesname = temlist[1].value
            car.specname = temlist[2].value
            intent.putExtra("car", car as Serializable)
            content.startActivityForResult(intent, 101)
        }

    }

    var carBrandParam: CarBrandParam? = null
    /**
     * 设置汽车品牌
     */
    fun setCarData(carBrandParam: CarBrandParam) {
        this.carBrandParam = carBrandParam
        temlist[0].value = carBrandParam.brandname
        temlist[0].id = carBrandParam.brand
        temlist[1].value = carBrandParam.seriesname
        temlist[1].id = carBrandParam.series
        temlist[2].value = carBrandParam.specname
        temlist[2].id = carBrandParam.spec


    }

    var view: View? = null
    /**
     * 确认修改
     */
    fun okBut(view: View) {
        this.view = view
        var hashMap = HashMap<String, String>()
        for (item in temlist) {
            if (!item.id.isNullOrBlank()) {
                hashMap[item.idname] = item.id
            }
        }
        //提车
        if (tiCar) {
            hashMap["updatetype"] = "drive"
        } else {
            hashMap["updatetype"] = "order"
        }
        hashMap["tid"] = clueDetails.tid.toString()
        hashMap["nkey"] = "archive.index"
        if(cert_images.size>0){
            hashMap.put("cert_image_url",cert_images.joinToString(","));
        }
//        hashMap["updatetype"] = "mobile"
        var fail: () -> Unit = {
            editBtnEnable.postValue(true)
        }
        view.isEnabled = false
        clueFollowUpRepository.editClue(hashMap, this::onSuccess,fail)
    }

    fun onSuccess(clueDetails: ClueDetails):Unit {
        view?.apply {
//            Looper.prepare()
//            var intent = Intent(context, MainActivity::class.java)
//            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
//            context.startActivity(intent)
//            Toast.makeText(MyApplication.getInstance(), "编辑成功", Toast.LENGTH_LONG).show()
//            Looper.loop()
            MyToast("编辑成功")
            LiveEventBus.get().with("clueupdatge").postValue("")
            myFinish()
        }
    }

}